package dvx.mp.ivisual.desktop.domain.invoices;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Text;

import org.apache.log4j.Logger;

import dvx.mp.ivisual.desktop.ui.model.IInvoice;


public class InvoiceService {

	private final Logger log;

	private InvoiceService()	{
		log = Logger.getLogger(InvoiceService.class);
	}

	private static InvoiceService instance;

	public synchronized static InvoiceService getInstance()	{
		if(null == instance)	{
			instance = new InvoiceService();
		}

		return instance;
	}

	public List<IInvoice> importInvoicesFromFiles(final File[] files)	{
		List<IInvoice> invoices = new ArrayList<IInvoice>();

		Builder builder = new Builder();
		try {
			for(File file : files)	{
				Document doc = builder.build(new FileInputStream(file));
				log.trace("Documento inicializado");

				Invoice singleInvoice = new Invoice();

				// Comprobante
				Element root = doc.getRootElement();

				Calendar cal = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
				cal.setTime(sdf.parse(root.getAttributeValue("fecha")));
				singleInvoice.setDate(cal);

				singleInvoice.setMonto(
						Double.parseDouble(root.getAttributeValue("subTotal")));

				singleInvoice.setTotal(
						Double.valueOf(root.getAttributeValue("total")));

				for(int i = 0; i < root.getChildCount(); i++)	{
					if(root.getChild(i).getClass().equals(Text.class))	{
						continue;
					}
					
					final Element elem = (Element) root.getChild(i);
					
					String elemName = elem.getQualifiedName().replaceAll("cfdi:", "");
					
					switch (elemName) {
					case "Complemento":
						for(int j = 0; j < elem.getChildCount(); j++)	{
							if(elem.getChild(j).getClass().equals(Text.class))	{
								continue;
							}
							
							final Element elemComp = (Element) elem.getChild(j);
							
							elemName = elemComp.getQualifiedName().replace("tfd:", "");
							
							if("TimbreFiscalDigital".equals(elemName))	{
								singleInvoice.setUUID(elemComp.getAttributeValue("UUID"));
							}
						}
						break;
					case "Emisor":
						final String rfcEmisor = elem.getAttributeValue("rfc");
						
						if("AAFF740627BE8".equals(rfcEmisor))	{
							singleInvoice.setIncome(true);
						}else	{
							singleInvoice.setRFC(elem.getAttributeValue("rfc"));
							singleInvoice.setConcepto(elem.getAttributeValue("nombre"));
						}
						break;
					case "Receptor":
						final String rfcReceptor = elem.getAttributeValue("rfc");
						
						if("AAFF740627BE8".equals(rfcReceptor))	{							
							singleInvoice.setIncome(false);
						}else	{
							singleInvoice.setRFC(elem.getAttributeValue("rfc"));
							singleInvoice.setConcepto(elem.getAttributeValue("nombre"));
						}
						break;
					case "Impuestos":
						for(int j = 0; j < elem.getChildCount(); j++)	{
							if(elem.getChild(j).getClass().equals(Text.class))	{
								continue;
							}
							
							final Element elemImp = (Element) elem.getChild(j);
							
							elemName = elemImp.getQualifiedName().replaceAll("cfdi:", "");
							
							switch (elemName) {
							case "Traslados":
								for(int k = 0; k < elemImp.getChildCount(); k++)	{
									if(elemImp.getChild(k).getClass().equals(Text.class))	{
										continue;
									}
									
									Element elemTras = (Element) elemImp.getChild(k);
									
									if(elemTras.getAttributeValue("impuesto").equals("IVA"))	{
										singleInvoice.setIVA(
												Double.valueOf(elemTras.getAttributeValue("importe")));
									}
								}
								break;
							default:
								break;
							}
						}
						break;
					default:
						break;
					}
				}

				invoices.add(singleInvoice);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return invoices;
	}

	public List<IInvoice> importInvoicesFromMailBox()	{
		return new ArrayList<IInvoice>();
	}
}
